import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		isPlaying: false,
		tempo: 120,
		beatsPerMeasure: 4,
		timeSignature: '4/4',
		sound: 'Woodblock',
		volume: 0.5,
		subdivision: '1/4',
		vibration: false,
		visualCue: false,
		currentBeat: 0,
		countdown: 0,
		mute: false,
		playbackSpeed: 1,
		audioContext:null
	},
	mutations: {
		setIsPlaying(state, isPlaying) {
			state.isPlaying = isPlaying;
		},
		setTempo(state, tempo) {
			state.tempo = tempo;
		},
		setBeatsPerMeasure(state, beatsPerMeasure) {
			state.beatsPerMeasure = beatsPerMeasure;
		},
		setTimeSignature(state, timeSignature) {
			state.timeSignature = timeSignature;
		},
		setSound(state, sound) {
			state.sound = sound;
		},
		setVolume(state, volume) {
			state.volume = volume;
		},
		setSubdivision(state, subdivision) {
			state.subdivision = subdivision;
		},
		setVibration(state, vibration) {
			state.vibration = vibration;
		},
		setVisualCue(state, visualCue) {
			state.visualCue = visualCue;
		},
		setCurrentBeat(state, currentBeat) {
			state.currentBeat = currentBeat;
		},
		setCountdown(state, countdown) {
			state.countdown = countdown;
		},
		setMute(state, mute) {
			state.mute = mute;
		},
		setPlaybackSpeed(state, playbackSpeed) {
			state.playbackSpeed = playbackSpeed;
		},
	},
	actions: {
		toggleMetronome({
			commit,
			state
		}) {
			commit('setIsPlaying', !state.isPlaying);
			if (state.isPlaying) {
				this.dispatch('startMetronome');
			} else {
				this.dispatch('stopMetronome');
			}
		},
		startMetronome({
			commit,
			state
		}) {
			const interval = (60 / state.tempo) * 1000 / state.playbackSpeed;
			this.metronomeInterval = setInterval(() => {
				commit('setCurrentBeat', (state.currentBeat + 1) % state.beatsPerMeasure);
				this.dispatch('playSound');
				if (state.visualCue) {
					this.dispatch('triggerVisualCue');
				}
				if (state.vibration) {
					this.dispatch('triggerVibration');
				}
			}, interval);
		},
		stopMetronome() {
			clearInterval(this.metronomeInterval);
		},
		playSound({
			state
		}) {
			if (state.mute) return;
			this.audioContext = uni.createInnerAudioContext();
			this.audioContext.src = `/static/sounds/${state.sound}.wav`; // 确保你有一个点击音频文件
			this.audioContext.volume = 100; // 设置初始音量
			this.audioContext.onCanplay(() => {
			});
			
		},
		triggerVisualCue() {
			// 实现视觉提示
			// 触发视觉提示的逻辑
			commit('setVisualCue', true); // 设置视觉提示状态为 true
			setTimeout(() => {
				commit('setVisualCue', false); // 200ms 后恢复视觉提示状态为 false
			}, 200);
		},
		triggerVibration() {
			if (navigator.vibrate) {
				navigator.vibrate(200); // 200ms 的振动
			}
		},
	},
});

export default store;